# Create your views here.
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View


def set_session(request):
    """session增值"""
    """dict 操作
   可以将 request.session 视作一个 dict，往里面添加 user_id，is_login 等
   用于标识用户是否登录的信息的时候可以直接操作，比如："""
    request.session['user_id'] = 14
    request.session['is_login'] = True
    """设置会话Session和Cookie的超时时间
   request.session.set_expiry(value)
    * 如果value是个整数，session会在些秒数后失效。
    * 如果value是个datatime或timedelta，session就会在这个时间后失效。
    * 如果value是0,用户关闭浏览器session就会失效。
    * 如果value是None,session会依赖全局session失效策略。"""
    # request.session.set_expiry(1)
    return HttpResponse('设置session')


def get_session(request):
    """session改值"""
    dict1 = {}
    #  所有 键、值、键值对
    dict1['keys'] = request.session.keys()
    dict1['values'] = request.session.values()
    dict1['items'] = request.session.items()
    # 获取session存储的值
    dict1['user_id'] = request.session.get('user_id')
    dict1['is_login'] = request.session.get('is_login')

    # 会话session的key
    dict1['session_key'] = request.session.session_key
    # 检查会话session的key在数据库中是否存在
    dict1['flag'] = request.session.exists(dict1['session_key'])

    # 获取 session 过期秒数，这个值就是前面我们在 settings.py 中设置的 SESSION_COOKIE_AGE 的值。
    dict1['expiry_age'] = request.session.get_expiry_age()
    # 返回此会话将过期的日期
    dict1['expiry_date'] = request.session.get_expiry_date()

    re = f'获取session对象中的值:{dict1}'
    [print(key, ":", value) for key, value in dict1.items()]
    return HttpResponse(re)


def del_session(request):
    """session删值"""
    """从 django_session 中移除过期的会话，
   django_session 会有一个 expire_date 字段，
    clear_expired() 这个操作就会删除表里 expire_date 小于当前时间的数据。"""
    # request.session.clear_expired()
    # 删除当前会话的所有Session数据
    # request.session.delete()

    # 删除当前的会话数据并删除会话的Cookie。
    request.session.flush()  # 常用，清空所有cookie---删除session表里的这个会话的记录，
    # 这用于确保前面的会话数据不可以再次被用户的浏览器访问
    # 例如，django.contrib.auth.logout()
    # 函数中就会调用它。

    return HttpResponse("session删值")


# 注册功能
def register(request):
    # 5.1 判断数据提交方式
    if request.method == "POST":
        # 5.2 获取用户数据
        post_obj = request.POST
        username = post_obj.get('username')
        password = post_obj.get('password')
        email = post_obj.get('email')
        # 5.3 操作User表
        from django.contrib.auth.models import User
        # User.objects.create(username=username,password=password,email=email)
        User.objects.create_user(username=username, password=password, email=email)
        return HttpResponseRedirect(reverse('session_demo_app:login'))
    return render(request, 'session_study/register.html')


# 登录功能
class Lgoin(View):
    def get(self, request):
        error_msg = request.session.get('error_msg')
        if error_msg:
            del request.session['error_msg']
        return render(request, './session_study/login.html', context={'error_msg': error_msg})

    def post(self, request):
        post_obj = request.POST
        username = post_obj.get('username')
        password = post_obj.get('password')
        from django.contrib import auth
        # 校验用户名和密码是否正确
        User_obj = auth.authenticate(username=username, password=password)
        print('User_obj-----', User_obj)
        print('username-----', username)
        print('password-----', password)
        if User_obj:
            # 保存session
            auth.login(request, User_obj)
            return redirect('session_demo_app:index')
        else:
            error_msg = '用户名或密码错误'
            request.session['error_msg'] = error_msg
            return redirect('session_demo_app:login')
            # return render(request, './captcha_study/login.html', locals())


# 注销功能
def logout(request):
    auth.logout(request)
    return redirect('session_demo_app:login')


# 修改密码功能
class SetPassword(View):
    def post(self,request):
        post_obj = request.POST
        old_password = post_obj.get('old_password')
        new_password= post_obj.get('new_password')
        confirm_password = post_obj.get('confirm_password')
        print('request.user',request.user )
        if not confirm_password==new_password:
            error_msg={'confirm_password':'两次密码不一样'}
            return render(request,'./session_study/set_password.html',{'error_msg':error_msg})
        flag=request.user.check_password(old_password)
        print('flag',flag )
        if not flag:
            error_msg = {'old_password': '密码不正确'}
            return render(request, './session_study/set_password.html', {'error_msg': error_msg})
        request.user.set_password(new_password)
        request.user.save()  # 一定要保存
        return HttpResponse('修改密码成功')


    def get(self,request):
         return render(request, './session_study/set_password.html')

# 登陆之后可以查看的页面
@login_required
def index(request):
    return render(request, 'session_study/index.html')
